﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SMS.DAL.Providers
{
    public class StockItemsProvider : ProviderBase<StockItem,StockItemsSearchCriteria>
    {
        public override void Insert(StockItem item)
        {
            Context.StockItems.AddObject(item);
            Context.SaveChanges();
        }

        public override void Update(StockItem updatedItem)
        {
            StockItem oldItem = (from stockitem in Context.StockItems
                                 where stockitem.ID == updatedItem.ID
                                 select stockitem).FirstOrDefault();

            oldItem.Count = updatedItem.Count;
            oldItem.MinCount = updatedItem.MinCount;
            oldItem.StockID = updatedItem.StockID;

            Context.SaveChanges();
        }

        public override void Delete(int id)
        {
            throw new NotImplementedException();
        }

        public override StockItem GetByID(int id)
        {
            return (from s in Context.StockItems
                    where s.ID == id
                    select s).FirstOrDefault();
        }

        public override List<StockItem> Search(StockItemsSearchCriteria SearchCriteria)
        {
            throw new NotImplementedException();
        }

        public List<StockItem> Search(string ItemName, string ItemMark,int StockID)
        {
            return (from s in Context.StockItems
                    where ((s.Item.Name == ItemName) && (s.Item.Mark == ItemMark) && (s.StockID == StockID))
                    select s).ToList();
        }

        public StockItem GetByItemIDAndStockID(StockItemsSearchCriteria SearchCriteria)
        {
            return (from stockitem in Context.StockItems
                    where ((stockitem.ItemID == SearchCriteria.ItemID) && (stockitem.StockID == SearchCriteria.StockID))
                    select stockitem).FirstOrDefault();
        }

        public StockItem GetByBarcode(ItemSearchCriteria ItemSearch)
        {
            var quary = (from item in Context.StockItems
                         where ((ItemSearch.Barcode == item.Item.BarCode) && (ItemSearch.StockID == item.StockID ))
                         select item);
            return quary.FirstOrDefault();
        }

        public List<StockItem> GetByStocks(List<Stock> stocks,int ItemID)
        {
            var stockItems = (from si in Context.StockItems
                              where si.ItemID == ItemID
                              select si).ToList();
            var quary = (from si in stockItems
                         join st in stocks on si.StockID equals st.ID
                         orderby si.Stock.ID
                         select si).ToList();
            return quary;
        }
    }
}
